package com.jinlia.show.modules.system.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jinlia.show.common.core.exception.MyRuntimeException;
import com.jinlia.show.common.core.utils.UserInfoUtils;
import com.jinlia.show.modules.base.system.entity.SysRole;
import com.jinlia.show.modules.base.system.entity.SysUser;
import com.jinlia.show.modules.base.system.service.SysUserMapperService;
import com.jinlia.show.modules.base.model.po.SysUserPO;
import com.jinlia.show.modules.base.model.query.UserPageQuery;
import com.jinlia.show.modules.system.model.vo.excel.UserExportVO;
import com.jinlia.show.modules.system.service.ifc.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class SysUserService extends SysUserMapperService implements ISysUserService {


    private final SysUserRoleService userRoleService;

    private final SysRoleMenuService roleMenuService;

    private final SysRoleService roleService;


    /**
     * 获取用户分页列表
     *
     * @param queryParams
     * @return
     */
    @Override
    public IPage<SysUserPO> getUserPage(UserPageQuery queryParams) {
        Page<SysUser> page = new Page<>(queryParams.getCurrent(), queryParams.getSize());
        //构造查询参数
        Page<SysUserPO> sysUserVOPage = this.getBaseMapper().getPagePO(page, queryParams);
        for (SysUserPO record : sysUserVOPage.getRecords()) {
            //填充vo的其他属性
            record.filedVO(record::getDeptName, record::getGenderLabel);
//            record.setRoles(Arrays.asList());
        }
        return sysUserVOPage;
    }

    /**
     * 获取用户详情
     *
     * @param userId
     * @return
     */
    @Override
    public SysUserPO getUserById(Long userId) {
        SysUser byId = this.getById(userId);
        SysUserPO sysUserVO = SysUserPO.fromEntity(byId);
        List<SysRole> rolesByUserId = roleService.getRolesByUserId(userId);
        sysUserVO.setRoles(rolesByUserId);
        return sysUserVO;
    }

    /**
     * 新增用户
     *
     * @param sysUserVO 用户表单对象
     * @return
     */
    @Override
    @Transactional
    public boolean saveUser(SysUserPO sysUserVO) {
        Long count = this.lambdaQuery().eq(SysUser::getUsername, sysUserVO.getUsername()).count();
        if (count > 0) {
            throw new MyRuntimeException("用户名已存在");
        }
        // 实体转换 form->entity
        sysUserVO.setPassword("123456");
        // 新增用户
        if (this.save(sysUserVO)) {
            // 保存用户角色
            List<Long> roleIds = sysUserVO.getRoles().stream().map(SysRole::getId).collect(Collectors.toList());
            userRoleService.saveUserRoles(sysUserVO.getId(), roleIds);
        }
        return false;
    }

    /**
     * 更新用户
     *
     * @param userId 用户ID
     * @param user   用户表单对象
     * @return
     */
    @Override
    @Transactional
    public boolean updateUser(Long userId, SysUserPO user) {
        Long count = this.lambdaQuery()
                .eq(SysUser::getUsername, user.getUsername())
                .ne(SysUser::getId, userId).count();
        if (count > 0) {
            throw new MyRuntimeException("用户名已存在");
        }
        // 修改用户
        boolean result = this.updateById(user);

        if (result) {
            // 保存用户角色
            List<Long> roleIds = user.getRoles().stream().map(SysRole::getId).collect(Collectors.toList());
            userRoleService.saveUserRoles(user.getId(), roleIds);
        }
        return true;
    }

    /**
     * 删除用户
     *
     * @param id 用户ID，多个以英文逗号(,)分割
     * @return
     */
    @Override
    public boolean deleteUsers(String id) {
        return this.removeById(id);

    }

    /**
     * 修改用户密码
     *
     * @param userId   用户ID
     * @param password 用户密码
     * @return true|false
     */
    @Override
    public boolean updatePassword(Long userId, String password) {
        boolean update = this.lambdaUpdate()
                .eq(SysUser::getId, userId)
                .set(SysUser::getPassword, password)
                .update();
        return update;
    }

    /**
     * 根据用户名获取认证信息
     *
     * @param username 用户名
     * @return 用户认证信息 {@link }
     */
//    @Override
//    public UserAuthInfo getUserAuthInfo(String username) {
//        UserAuthInfo userAuthInfo = this.baseMapper.getUserAuthInfo(username);
//        if (userAuthInfo != null) {
//            Set<String> roles = userAuthInfo.getRoles();
//            if (CollectionUtil.isNotEmpty(roles)) {
//                Set<String> perms = menuService.listRolePerms(roles);
//                userAuthInfo.setPerms(perms);
//            }
//
//            // 获取最大范围的数据权限
//            Integer dataScope = roleService.getMaximumDataScope(roles);
//            userAuthInfo.setDataScope(dataScope);
//        }
//        return userAuthInfo;
//    }


    /**
     * 获取导出用户列表
     *
     * @param queryParams
     * @return
     */
    @Override
    public List<UserExportVO> listExportUsers(UserPageQuery queryParams) {
//        List<UserExportVO> list = this.baseMapper.listExportUsers(queryParams);
//        return list;
        return null;
    }

    @Override
    public SysUserPO getCurrentUserInfo() {
        Long userId = UserInfoUtils.getUserId();
        SysUser byId = this.getById(userId);
        SysUserPO sysUserVO = SysUserPO.fromEntity(byId);
        //用户角色
        List<SysRole> rolesByUserId = roleService.getRolesByUserId(userId);
        sysUserVO.setRoles(rolesByUserId);
        //button的权限标识
        Set<Long> roleIds = rolesByUserId.stream().map(SysRole::getId).collect(Collectors.toSet());
        List<String> buttonPerms = roleMenuService.getButtonPermsByRoleIds(roleIds.toArray(new Long[roleIds.size()]));
        sysUserVO.setPerms(buttonPerms);
        return sysUserVO;
    }

//    /**
//     * 获取登录用户信息
//     *
//     * @return {@link UserInfoVO}   用户信息
//     */
//    @Override
//    public UserInfoVO getCurrentUserInfo() {
//
//        String username = SecurityUtils.getUser().getUsername(); // 登录用户名
//
//        // 获取登录用户基础信息
//        SysUser user = this.getOne(new LambdaQueryWrapper<SysUser>()
//                .eq(SysUser::getUsername, username)
//                .select(
//                        SysUser::getId,
//                        SysUser::getUsername,
//                        SysUser::getNickname,
//                        SysUser::getAvatar
//                )
//        );
//        // entity->VO
//        UserInfoVO userInfoVO = userConverter.toUserInfoVo(user);
//
//        // 用户角色集合
//        Set<String> roles = SecurityUtils.getRoles();
//        userInfoVO.setRoles(roles);
//
//        // 用户权限集合
//        if (CollectionUtil.isNotEmpty(roles)) {
//            Set<String> perms = permissionService.getRolePermsFormCache(roles);
//            userInfoVO.setPerms(perms);
//        }
//        return userInfoVO;
//    }
}
